from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
import json
import random
import os
from datetime import datetime, timedelta

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 数据文件路径
ROLL_CALL_FILE = 'roll_call_data.json'


# 初始化数据
def init_data():
    if not os.path.exists(ROLL_CALL_FILE):
        # 默认名字列表
        default_names = [
            "张三", "李四", "王五", "赵六", "钱七",
            "孙八", "周九", "吴十", "郑十一", "王十二"
        ]

        data = {
            "names": default_names,
            "roll_call_history": [],
            "qa_history": []
        }

        with open(ROLL_CALL_FILE, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    return load_data()


# 加载数据
def load_data():
    try:
        with open(ROLL_CALL_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        return {"names": [], "roll_call_history": [], "qa_history": []}


# 保存数据
def save_data(data):
    with open(ROLL_CALL_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)


# 检查名字是否在3天内被点过
def is_name_recently_called(name, history):
    three_days_ago = datetime.now() - timedelta(days=3)

    for record in history:
        record_date = datetime.strptime(record['date'], '%Y-%m-%d')
        if record['name'] == name and record_date >= three_days_ago:
            return True

    return False


# 首页
@app.route('/')
def index():
    return render_template('index.html')


# 获取所有名字
@app.route('/api/names', methods=['GET'])
def get_names():
    data = load_data()
    return jsonify(data['names'])


# 导入名字
@app.route('/api/names/import', methods=['POST'])
def import_names():
    data = request.get_json()
    names_list = data.get('names', [])

    if not names_list:
        return jsonify({'error': '没有提供名字列表'}), 400

    # 读取现有数据
    existing_data = load_data()

    # 添加新名字（去重）
    for name in names_list:
        if name and name not in existing_data['names']:
            existing_data['names'].append(name)

    # 保存数据
    save_data(existing_data)

    return jsonify({
        'message': f'成功导入 {len(names_list)} 个名字',
        'total_names': len(existing_data['names'])
    })


# 点名区随机点名
@app.route('/api/roll_call/random', methods=['GET'])
def roll_call_random():
    data = load_data()
    names = data['names']

    if not names:
        return jsonify({'error': '没有名字数据'}), 404

    # 过滤掉3天内被点过的名字
    available_names = [
        name for name in names
        if not is_name_recently_called(name, data['roll_call_history'])
    ]

    # 如果没有可用名字，使用所有名字
    if not available_names:
        available_names = names

    # 随机选择名字
    selected_name = random.choice(available_names)

    # 记录点名历史
    data['roll_call_history'].append({
        'name': selected_name,
        'date': datetime.now().strftime('%Y-%m-%d'),
        'type': 'roll_call'
    })

    save_data(data)

    return jsonify({
        'name': selected_name,
        'is_recent': is_name_recently_called(selected_name, data['roll_call_history'][:-1])
    })


# 问答区随机点名
@app.route('/api/qa/random', methods=['GET'])
def qa_random():
    data = load_data()
    names = data['names']

    if not names:
        return jsonify({'error': '没有名字数据'}), 404

    # 随机选择名字
    selected_name = random.choice(names)

    # 记录问答历史
    data['qa_history'].append({
        'name': selected_name,
        'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'type': 'qa'
    })

    save_data(data)

    return jsonify({'name': selected_name})


# 获取点名历史
@app.route('/api/history/roll_call', methods=['GET'])
def get_roll_call_history():
    data = load_data()
    return jsonify(data['roll_call_history'][-10:])  # 返回最近10条记录


# 获取问答历史
@app.route('/api/history/qa', methods=['GET'])
def get_qa_history():
    data = load_data()
    return jsonify(data['qa_history'][-10:])  # 返回最近10条记录


# 删除点名记录 - 修复索引问题
@app.route('/api/history/roll_call/delete', methods=['POST'])
def delete_roll_call_record():
    data = request.get_json()
    index = data.get('index')

    if index is None:
        return jsonify({'error': '缺少索引参数'}), 400

    # 加载数据
    all_data = load_data()

    # 计算实际索引（前端传递的是反转后的索引）
    actual_index = index

    # 检查索引是否有效
    if actual_index < 0 or actual_index >= len(all_data['roll_call_history']):
        return jsonify({'error': '无效的索引'}), 400

    # 删除指定记录
    del all_data['roll_call_history'][actual_index]

    # 保存数据
    save_data(all_data)

    return jsonify({'message': '删除成功'})


# 删除问答记录 - 修复索引问题
@app.route('/api/history/qa/delete', methods=['POST'])
def delete_qa_record():
    data = request.get_json()
    index = data.get('index')

    if index is None:
        return jsonify({'error': '缺少索引参数'}), 400

    # 加载数据
    all_data = load_data()

    # 计算实际索引（前端传递的是反转后的索引）
    actual_index = index

    # 检查索引是否有效
    if actual_index < 0 or actual_index >= len(all_data['qa_history']):
        return jsonify({'error': '无效的索引'}), 400

    # 删除指定记录
    del all_data['qa_history'][actual_index]

    # 保存数据
    save_data(all_data)

    return jsonify({'message': '删除成功'})


# 清空所有数据
@app.route('/api/clear/roll_call_history', methods=['POST'])
def clear_roll_call_history():
    # 加载现有数据
    all_data = load_data()

    # 清空点名历史记录
    all_data["roll_call_history"].clear()

    # 保存更新后的数据
    save_data(all_data)

    return jsonify({'message': '提问记录已清空'})

@app.route('/api/clear/qa_history', methods=['POST'])
def clear_qa_history():
    # 加载现有数据
    all_data = load_data()

    # 清空提问历史记录
    all_data["qa_history"].clear()

    # 保存更新后的数据
    save_data(all_data)

    return jsonify({'message': '提问记录已清空'})


if __name__ == '__main__':
    init_data()
    app.run(debug=True, port=5000)
    # app.run(host='0.0.0.0', port=5000)